<!--
 * @Author: wangming
 * @Date: 2021-05-19 10:43:21
 * @LastEditors: wangming
 * @LastEditTime: 2021-10-14 17:49:35
 * @Description: file content
-->
<template>
  <el-tree
    node-key="key"
    :data="tree"
    @node-click="handleNodeClick"
    highlight-current
    default-expand-all
    :expand-on-click-node="false"
    check-on-click-node
    ref="tree"
  >
    <span slot-scope="{ data }">
      <span>{{
        data.__config
          ? data.__config.label || data.name
          : data.name || data.label
      }}</span>
    </span>
  </el-tree>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { cloneDeep } from "lodash";
export default {
  data() {
    return {};
  },
  computed: {
    ...mapGetters(["getModelTreeList", "getModelForm", "getFormId"]),
    tree() {
      return [{ name: "页面大纲", key: 0, children: this.getModelTreeList }];
    },
  },
  watch: {
    "getModelForm.key": function (val) {
      this.$refs.tree.setCurrentKey(val);
    },
  },
  methods: {
    ...mapActions(["setModelForm", "setForm"]),
    async handleNodeClick(form) {
      //当点击表单内组件当时候需要处理好表单所属业务模型的数据模型数据
      if (form.isFormLayout) {
        let { modelCode, children } = this.getFormModelCodeInTree(
          form.key,
          this.getModelTreeList
        );
        this.$store.commit("changeFormList", children);
        if (this.getFormId !== modelCode) {
          //表单组件逻辑
          this.setForm(modelCode);
        }
      }
      if (form.key !== this.getModelForm.key) {
        this.setModelForm({});
        await this.$nextTick();
      }
      this.setModelForm(form);
    },

    /**
     *  在tree中 根据 组件key 定位所点击组件所在的form
     * @param {*} key
     * @param {*} treelist
     * @returns  返回组件所在formlayout  的   modelCode  和 children
     */
    getFormModelCodeInTree(key, treelist) {
      let queen = [],
        node = null;
      queen = queen.concat(treelist);
      while (queen?.length > 0) {
        let item = queen.shift();
        if (item._TYPE_ === "org") {
          node = item.node;
        } else if (item.key === key && !!node) {
          queen = [];
        } else if (item.children) {
          let org = [];
          if (
            item.tagName === "hlTableAdd" ||
            item.tagName === "hlLayoutForm"
          ) {
            org.push({ node: cloneDeep(node), _TYPE_: "org" });
            let nodeCode = item.__config.modelCode || item.__config.code; // 兼容老业务
            !!nodeCode &&
              (node = { modelCode: nodeCode, children: item.children });
          }
          queen = [].concat(item.children, org, queen);
        }
      }
      return node;
    },
  },
};
</script>

<style lang="scss" scoped></style>
